/** @odoo-module **/

import { Component, onMounted, useRef, useState, onWillUnmount } from "@odoo/owl";
import { registry } from "@web/core/registry";
import { useService } from "@web/core/utils/hooks";
import { loadJS } from "@web/core/assets";
import { Dialog } from "@web/core/dialog/dialog";
import mobile from "@web_mobile/js/services/core";
import { _t } from "@web/core/l10n/translation";

/**
 * 条码扫描对话框组件
 */
export class BarcodeScannerDialog extends Component {
    setup() {
        super.setup();
        this.notification = useService("notification");
        this.orm = useService("orm");
        this.actionService = useService("action");
        this.reader = useRef("barcode_reader");
        this.qrScanner = null;
        this.state = useState({
            isScanning: false,
        });

        onMounted(() => {
            this.loadBarcodeScanner();
        });

        onWillUnmount(() => {
            if (this.qrScanner) {
                try {
                    this.qrScanner.clear();
                } catch (err) {
                    console.error("Error clearing scanner:", err);
                }
            }
        });
    }

    async loadBarcodeScanner() {
        try {
            await loadJS("https://cdn.jsdelivr.net/npm/html5-qrcode@2.3.8/html5-qrcode.min.js");
            
            this.state.isScanning = true;
            
            const qrScanner = new Html5QrcodeScanner(this.reader.el.id, {
                qrbox: { width: 250, height: 250 },
                fps: 20,
                rememberLastUsedCamera: true,
                showTorchButtonIfSupported: true,
            });
            
            qrScanner.render(
                (data) => this.onScanSuccess(data),
                (err) => {
                    if (err && !err.includes("NotFoundException")) {
                        console.warn("Scan Error:", err);
                    }
                }
            );
            
            this.qrScanner = qrScanner;
            
        } catch (error) {
            console.error("Error loading barcode scanner:", error);
            this.notification.add("加载扫描器失败：" + error.message, { type: "danger" });
        }
    }

    async onScanSuccess(barcodeData) {
        console.log("Scan successful:", barcodeData);
        
        try {
            if (this.qrScanner) {
                this.qrScanner.clear();
            }
            
            const parts = barcodeData.split(',');
            if (parts.length !== 3) {
                this.notification.add("条码格式错误！期望格式：姓名,性别,班级", { type: "danger" });
                this.props.close();
                return;
            }
            
            const [name, gender, class_id] = parts;
            
            const validGenders = ['male', 'female', 'other'];
            if (!validGenders.includes(gender.toLowerCase())) {
                this.notification.add(`性别值无效！有效值：male, female, other。实际值：${gender}`, { type: "danger" });
                this.props.close();
                return;
            }
            
            const updateData = {
                name: name.trim(),
                gender: gender.toLowerCase().trim(),
                class_id: class_id.trim(),
            };
            
            const resId = this.props.action.params.res_id;
            
            if (resId) {
                await this.orm.write('hostel.student', [resId], updateData);
                this.notification.add(`扫描成功！姓名：${name}，性别：${gender}，班级：${class_id}`, { type: "success" });
                this.props.close();
                await this.actionService.doAction({
                    type: 'ir.actions.act_window',
                    res_model: 'hostel.student',
                    res_id: resId,
                    views: [[false, 'form']],
                    target: 'current',
                });
            }
            
        } catch (error) {
            console.error("Error processing barcode:", error);
            this.notification.add("处理条码数据时出错：" + error.message, { type: "danger" });
            this.props.close();
        }
    }
}

BarcodeScannerDialog.template = "my_hostel.BarcodeScannerDialog";
BarcodeScannerDialog.components = { Dialog };
BarcodeScannerDialog.props = {
    close: Function,
    action: Object,
};

// 注册客户端动作
registry.category("actions").add("barcode_scanner_action", async function (env, action) {
    console.log("Barcode scanner action triggered", action);
    
    try {
        const resId = action.params?.res_id;
        const isNewRecord = action.params?.is_new_record;
        
        if (!resId && isNewRecord) {
            const orm = env.services.orm;
            const tempId = await orm.call('hostel.student', 'create_temp_for_scanner', []);
            action.params.res_id = tempId;
        }
        
        env.services.dialog.add(BarcodeScannerDialog, { action });
        
    } catch (error) {
        console.error("Error in barcode scanner action:", error);
        env.services.notification.add("打开扫描器时出错：" + error.message, { type: "danger" });
    }
});

// 注册直接扫描客户端动作
registry.category("actions").add("barcode_scanner_direct_action", async function (env, action) {
    console.log("Direct barcode scanner action triggered", action);
    
    try {
        const resId = action.params?.res_id;
        
        if (!resId) {
            env.services.notification.add("无法获取记录ID", { type: "danger" });
            return;
        }
        
        env.services.dialog.add(BarcodeScannerDialog, { action });
        
    } catch (error) {
        console.error("Error in barcode scanner action:", error);
        env.services.notification.add("打开扫描器时出错：" + error.message, { type: "danger" });
    }
});

/**
 * 全局函数：直接打开条码扫描器（新版，不创建临时记录）
 */
window.openBarcodeScannerDirect = async function(record, orm) {
    console.log("Opening barcode scanner directly");
    
    try {
        // 创建自定义对话框（不依赖 Bootstrap JavaScript）
        const modalHtml = `
            <div class="o_barcode_modal_overlay" style="position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.5); z-index: 9999; display: flex; align-items: center; justify-content: center;">
                <div class="o_barcode_modal_dialog" style="background: white; border-radius: 8px; max-width: 800px; width: 90%; max-height: 90vh; overflow: auto; box-shadow: 0 10px 40px rgba(0,0,0,0.3);">
                    <div class="o_barcode_modal_header" style="background: #007bff; color: white; padding: 15px 20px; border-radius: 8px 8px 0 0; display: flex; justify-content: space-between; align-items: center;">
                        <h5 style="margin: 0; font-size: 18px;">
                            <i class="fa fa-barcode" style="margin-right: 8px;"></i>扫描学生信息条码
                        </h5>
                        <button type="button" class="o_barcode_modal_close" style="background: transparent; border: none; color: white; font-size: 24px; cursor: pointer; padding: 0; width: 30px; height: 30px; line-height: 1;">&times;</button>
                    </div>
                    <div class="o_barcode_modal_body" style="padding: 20px;">
                        <div style="background: #d1ecf1; border: 1px solid #bee5eb; border-radius: 4px; padding: 15px; margin-bottom: 20px; text-align: center;">
                            <h6 style="color: #0c5460; margin-bottom: 10px;"><i class="fa fa-info-circle"></i> 使用说明</h6>
                            <p style="margin: 5px 0; color: #0c5460;">📷 <strong>方式1：</strong> 将条码对准摄像头进行扫描</p>
                            <p style="margin: 5px 0; color: #0c5460;">📁 <strong>方式2：</strong> 点击"选择文件"上传条码图片</p>
                            <hr style="margin: 10px 0; border-color: #bee5eb;"/>
                            <p style="margin: 5px 0; font-size: 13px; color: #0c5460;"><strong>条码格式：</strong> 姓名,性别,班级</p>
                            <p style="margin: 5px 0; font-size: 13px; color: #0c5460;"><strong>示例：</strong> 张三,male,Class A</p>
                        </div>
                        <div id="barcode_reader_custom" style="max-width: 600px; margin: 0 auto;"></div>
                        <div id="scanning_status_custom" style="text-align: center; margin-top: 20px;">
                            <div class="spinner-border text-primary" role="status" style="width: 3rem; height: 3rem; border-width: 0.3em;">
                                <span style="position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0,0,0,0); white-space: nowrap; border: 0;">正在初始化扫描器...</span>
                            </div>
                            <p style="margin-top: 15px; color: #6c757d;">正在初始化扫描器...</p>
                        </div>
                    </div>
                </div>
            </div>
        `;
        
        // 移除已存在的对话框
        const existingModal = document.querySelector('.o_barcode_modal_overlay');
        if (existingModal) {
            existingModal.remove();
        }
        
        // 添加对话框到页面
        document.body.insertAdjacentHTML('beforeend', modalHtml);
        
        // 获取对话框元素
        const modalOverlay = document.querySelector('.o_barcode_modal_overlay');
        const closeButton = modalOverlay.querySelector('.o_barcode_modal_close');
        
        // 关闭按钮事件
        const closeModal = () => {
            if (window.currentScanner) {
                try {
                    // Html5Qrcode 使用 stop() 方法
                    if (typeof window.currentScanner.stop === 'function') {
                        window.currentScanner.stop().catch(err => console.error("Error stopping scanner:", err));
                    }
                    // Html5QrcodeScanner 使用 clear() 方法
                    else if (typeof window.currentScanner.clear === 'function') {
                        window.currentScanner.clear();
                    }
                } catch (err) {
                    console.error("Error stopping scanner:", err);
                }
                window.currentScanner = null;
            }
            modalOverlay.remove();
        };
        
        closeButton.addEventListener('click', closeModal);
        modalOverlay.addEventListener('click', (e) => {
            if (e.target === modalOverlay) {
                closeModal();
            }
        });
        
        // 加载 html5-qrcode 库并启动扫描
        await loadBarcodeScannerDirect(record, orm, closeModal);
        
    } catch (error) {
        console.error("Error opening barcode scanner:", error);
        alert("打开扫描器时出错：" + error.message);
    }
};

/**
 * 加载条码扫描器（直接版本，不创建临时记录）
 */
async function loadBarcodeScannerDirect(record, orm, closeModal) {
    try {
        // 动态加载html5-qrcode库
        if (typeof Html5Qrcode === 'undefined') {
            const script = document.createElement('script');
            script.src = 'https://cdn.jsdelivr.net/npm/html5-qrcode@2.3.8/html5-qrcode.min.js';
            document.head.appendChild(script);
            
            await new Promise((resolve, reject) => {
                script.onload = resolve;
                script.onerror = reject;
            });
        }
        
        // 更新状态
        const statusElement = document.getElementById('scanning_status_custom');
        if (statusElement) {
            statusElement.innerHTML = `
                <div class="spinner-border text-primary" role="status" style="width: 3rem; height: 3rem; border-width: 0.3em;">
                    <span style="position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0,0,0,0); white-space: nowrap; border: 0;">正在启动摄像头...</span>
                </div>
                <p style="margin-top: 15px; color: #6c757d;">正在启动摄像头，请稍候...</p>
            `;
        }
        
        // 使用 Html5Qrcode 而不是 Html5QrcodeScanner（更好的控制）
        const html5QrCode = new Html5Qrcode("barcode_reader_custom");
        
        // 获取可用摄像头
        const devices = await Html5Qrcode.getCameras();
        console.log("Available cameras:", devices);
        
        // 选择后置摄像头（environment）作为默认
        let selectedCameraId = null;
        
        // 优先选择后置摄像头
        const backCamera = devices.find(device => 
            device.label.toLowerCase().includes('back') || 
            device.label.toLowerCase().includes('rear') ||
            device.label.toLowerCase().includes('后')
        );
        
        if (backCamera) {
            selectedCameraId = backCamera.id;
            console.log("Using back camera:", backCamera.label);
        } else if (devices.length > 0) {
            // 如果没有找到后置摄像头，使用最后一个（通常是后置）
            selectedCameraId = devices[devices.length - 1].id;
            console.log("Using camera:", devices[devices.length - 1].label);
        }
        
        if (!selectedCameraId) {
            alert("未检测到可用的摄像头");
            closeModal();
            return;
        }
        
        // 配置扫描器
        const config = {
            fps: 10,    // 扫描帧率
            qrbox: { width: 250, height: 250 },  // 扫描框大小
            aspectRatio: 1.0,
        };
        
        // 启动扫描器
        await html5QrCode.start(
            selectedCameraId,
            config,
            (decodedText, decodedResult) => {
                // 扫描成功回调
                onScanSuccessDirect(decodedText, record, orm, closeModal, html5QrCode);
            },
            (errorMessage) => {
                // 扫描失败回调（不显示，避免日志刷屏）
            }
        );
        
        // 更新状态为正在扫描
        if (statusElement) {
            statusElement.innerHTML = `
                <div style="text-align: center; margin-top: 20px;">
                    <p style="color: #28a745; font-weight: bold; font-size: 16px;">
                        <i class="fa fa-camera" style="margin-right: 8px;"></i>摄像头已启动，请对准条码
                    </p>
                    <p style="color: #6c757d; font-size: 14px; margin-top: 10px;">
                        或点击下方按钮上传条码图片
                    </p>
                    <button onclick="document.getElementById('barcode_file_upload').click()" 
                            style="margin-top: 10px; padding: 10px 20px; background: #007bff; color: white; border: none; border-radius: 4px; cursor: pointer;">
                        <i class="fa fa-upload" style="margin-right: 5px;"></i>上传条码图片
                    </button>
                    <input type="file" id="barcode_file_upload" accept="image/*" style="display: none;">
                </div>
            `;
            
            // 添加文件上传事件
            document.getElementById('barcode_file_upload').addEventListener('change', async (e) => {
                const file = e.target.files[0];
                if (file) {
                    try {
                        const decodedText = await html5QrCode.scanFile(file, false);
                        onScanSuccessDirect(decodedText, record, orm, closeModal, html5QrCode);
                    } catch (err) {
                        alert("无法识别图片中的条码，请确保图片清晰且包含有效的条码");
                    }
                }
            });
        }
        
        // 存储扫描器引用
        window.currentScanner = html5QrCode;
        
    } catch (error) {
        console.error("Error loading barcode scanner:", error);
        if (error.name === 'NotAllowedError') {
            alert("摄像头权限被拒绝，请在浏览器设置中允许访问摄像头");
        } else if (error.name === 'NotFoundError') {
            alert("未检测到摄像头设备");
        } else {
            alert("加载扫描器失败：" + error.message);
        }
        closeModal();
    }
}

/**
 * 扫描成功回调（直接版本）
 */
async function onScanSuccessDirect(barcodeData, record, orm, closeModal, html5QrCode) {
    console.log("Scan successful:", barcodeData);
    
    try {
        // 停止扫描器
        try {
            await html5QrCode.stop();
        } catch (stopErr) {
            console.warn("Error stopping scanner:", stopErr);
        }
        
        // 解析条码数据
        const parts = barcodeData.split(',');
        if (parts.length !== 3) {
            alert("条码格式错误！\n期望格式：姓名,性别,班级\n实际数据：" + barcodeData);
            closeModal();
            return;
        }
        
        const [name, gender, class_id] = parts;
        
        // 验证性别
        const validGenders = ['male', 'female', 'other'];
        if (!validGenders.includes(gender.toLowerCase())) {
            alert("性别值无效！\n有效值：male, female, other\n实际值：" + gender);
            closeModal();
            return;
        }
        
        // 准备更新数据
        const updateData = {
            name: name.trim(),
            gender: gender.toLowerCase().trim(),
            class_id: class_id.trim(),
        };
        
        console.log("Updating student record with:", updateData);
        
        // 直接更新当前记录（不保存到数据库）
        await record.update(updateData);
        
        // 关闭对话框
        closeModal();
        
        // 显示成功消息
        alert("✅ 扫描成功！\n姓名：" + name + "\n性别：" + gender + "\n班级：" + class_id + "\n\n数据已填充，请点击\"保存\"按钮保存记录。");
        
    } catch (error) {
        console.error("Error processing barcode:", error);
        alert("处理条码数据时出错：" + error.message);
        closeModal();
    }
}

